package pro.cherish.protobuf.server;

import com.sanshengshui.netty.protobuf.UserMsg;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author 创建人：lys
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-6-16 lys 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：NettyServerInitializer
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-6-16 
 */
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		// 入参说明：读超时时间、写超时时间、所有类型的超时时间，时间格式
		pipeline.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
		// 解码和编码，应和客户端一致
		//传输的协议 Protobuf
		pipeline.addLast(new ProtobufVarint32FrameDecoder());
		pipeline.addLast(new ProtobufDecoder(UserMsg.User.getDefaultInstance()));
		pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
		pipeline.addLast(new ProtobufEncoder());
		// 业务逻辑实现类
		pipeline.addLast("nettyServerHandler",new NettyServerHandler());
	}
}
